<template>
  <el-dialog title="插播节目" width="500"  v-model="isVisible" @close="onCancelModel" append-to-body>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="选择文件" name="file"></el-tab-pane>
      <el-tab-pane label="选择计划" name="schedule"></el-tab-pane>
    </el-tabs>
    <div class="yy-device-bc">
      <div class="yy-device-bc_file" v-if="activeName === 'file'">
        <div class="yy-template-file">

          <div class="yy-template-file_item">
            <label>节目名称:</label>
            <div style="flex: 1; min-width: 0;"><el-input v-model="settings.name" style="min-width: 120px;"/></div>
          </div>
          <div class="yy-template-file_item" style="align-items: baseline;">
            <label>选择资源:</label>
            <div style="flex-direction: column;" v-if="isVisible">
              <div class="yy-template-file_item-resource" v-for="form in forms" :key="form.id">
                <div class="yy-template-file_item-file" style="flex: 1; min-width: 100px;">
                  <el-tree-select
                      v-model="form.fileViewId"
                      lazy
                      filterable
                      :load="load"
                      :props="props"
                      style="flex:1;"
                  >
                    <template #default="{ data: { label, isLeaf } }">
                      <span>
                        <el-icon v-if="!isLeaf"><Folder /></el-icon>
                        <el-icon v-else><Document /></el-icon>
                      </span>
                      <span>{{ label }}</span>
                    </template>
                  </el-tree-select>
                </div>
                <div class="yy-template-file_item-interval" style="margin: 0 10px;">
                  <el-input-number v-model="form.interval" :min="5"   style="width: 120px;"/>
                </div>
                <div class="yy-template-file_item-action">
                  <span v-if="forms.length > 1" class="yy-template-file_item-action--del" @click="onRemoveItem(form.id)"><el-icon ><Remove /></el-icon></span>
                  <span class="yy-template-file_item-action--add" @click="onAddSelectItem(form.id)"><el-icon ><CirclePlus /></el-icon></span>
                </div>
              </div>
            </div>
          </div>

          <div class="yy-template-file_item">
            <label>播放时间:</label>
            <div style="flex: 1; min-width: 0;">
              <span>
                 <el-date-picker
                     v-model="settings.startTime"
                     type="datetime"
                     placeholder="开始日期"
                     format="YYYY-MM-DD HH:mm"
                     date-format="YYYY-MM-DD"
                     time-format="HH:mm"
                     :default-time="startTimeDefault"
                     style="width: 100%"
                 />
              </span>
              <span style="margin: 0 15px;"> - </span>
              <span>
                 <el-date-picker
                     v-model="settings.endTime"
                     type="datetime"
                     placeholder="结束日期"
                     format="YYYY-MM-DD HH:mm"
                     date-format="YYYY-MM-DD"
                     time-format="HH:mm"
                     style="width: 100%"
                     :default-time="endTimeDefault"
                 />
              </span>
            </div>
          </div>

          <div class="yy-template-file_item" style="align-items: baseline;">
            <label>播放间隔:</label>
            <div style="flex-direction: column;">
              <div> <el-input-number v-model="settings.interval"  :min="1"  style="width: 120px;"/><span> 秒</span></div>
              <div style="color: #a0a1a7;">该设置只对非视频内容有效，视频默认必须播放完成后才会自动切换下一屏。</div>
            </div>
          </div>
        </div>
      </div>
      <div class="yy-device-bc_schedule" v-else>
        <el-select v-model="selectScheduleId" placeholder="请选择计划" style="width: 100%">
          <el-option
              v-for="item in scheduleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onCancelModel">取消</el-button>
        <el-button type="primary" @click="onSaveProgram">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {defineExpose, nextTick, ref} from "vue";
import {useRouter} from "vue-router";
import ResourceApi from "@/api/broadcast/resource";
import ScheduleApi from "@/api/broadcast/schedule";
import TemplateApi from "@/api/broadcast/template";
import {DeviceModel} from "@/model/DeviceModel";
import {ElMessage} from "element-plus";
import useUserStore from "@/store/modules/user";

const router = useRouter()
const isVisible = ref(false)
const startTimeDefault = new Date(2000, 1, 1, 0, 0 , 0)
const endTimeDefault = new Date(2000, 1, 1, 23, 59 , 59)

const $emit = defineEmits({
  operatorCallback:(type) => type
})
let device = null
const activeName = ref('file')
const props = {
  label: 'label',
  children: 'children',
  isLeaf: 'isLeaf',
}
const forms = ref([
  {
    id: '1',
    fileViewId: '',
    interval: null
  }
])

const settings = ref({
  interval: 5,
  name: '',
  startTime: '',
  endTime: '',
  deviceCodes: []
})

const scheduleList = ref([])
const selectScheduleId = ref()

const handleClick = () => {
    if (activeName.value === 'schedule' && !scheduleList.value?.length) {
      listScheduleData()
    }
}


const load = (node, resolve) => {
  if (node.isLeaf) return resolve([])
  ResourceApi.listFile(node ? node.data.fileId : null, device.deptId, null,1, 10000).then((res) => {
    const files = res.rows? res.rows.map(item => ({
      label: item.fileName,
      value: item.viewKey + "__" + item.fileName,
      fileId: item.resId,
      disabled: +item.resCategory === 1,
      isLeaf: +item.resCategory === 2,
      children: +item.resCategory === 2 ? undefined : []
    })) : []
    resolve(files)
  })
}

const onAddSelectItem = (id: string) => {
  const index = forms.value.findIndex(item => item.id === id)
  if (index >= 0) {
    if (index < forms.value.length - 1) {
      forms.value.splice(index + 1, 0, {
        id: getRowId(),
        fileViewId: '',
        interval: null
      })
    } else {
      forms.value.push({
        id: getRowId(),
        fileViewId: '',
        interval: null
      })
    }
  }
}

const onRemoveItem = (id: string) => {
  const index = forms.value.findIndex(item => item.id === id)
  if (index >= 0) {
    forms.value.splice(index, 1)
  }
}

const onShowDialog = (data: DeviceModel) => {
  device = data
  isVisible.value = true
}

const onCancelModel = () => {
  isVisible.value = false
}

const listScheduleData = (pageIndex: number = 1) => {
  ScheduleApi.listSchedule(null, pageIndex, 9999).then((res: any) => {
    scheduleList.value = res.data ? res.data.map(item => ({label: item.name, value: item.id})) : []
  })
}

const getRowId = () => {
  return new Date().getTime() + '_' + Math.random()
}

const onSaveProgram = () => {

  if (activeName.value === 'file') {
    const newDataArr = forms.value
        .filter(item => !!item.fileViewId)
        .map(item => {
          const vieIdAndFileName = item.fileViewId.split('__')
          return {
            fileViewId: vieIdAndFileName[0],
            fileName: vieIdAndFileName[1],
            interval: item.interval
          }
        })

    const data = Object.assign({}, settings.value, {
      deviceCodes: [device.code],
      files: newDataArr,
    })
    TemplateApi.insertTemplateByFile(data).then((res) => {
      ElMessage.success("插播创建成功!")
      onCancelModel()
    })
  } else {
    TemplateApi.insertTemplateBySchedule(selectScheduleId.value, device.id).then((res) => {
      ElMessage.success("插播创建成功!")
      onCancelModel()
    })
  }
}

defineExpose({
  onShowDialog
})
</script>
<style scoped lang="scss">
.yy-device-bc_file {
  padding: 15px 0;
}
.yy-device-bc_schedule {
  padding: 15px;
}
.yy-template-file {
  width: 100%;
  height: 100%;
  border: 0;
  display: flex;
  flex-direction: column;
  align-items: center;

  &_item {
    display: flex;
    flex-direction: row;
    margin-top: 10px;
    width: 100%;
    align-items: center;
    &-resource {
      display: flex;
      flex-direction: row;
      margin-bottom: 10px;
    }
    &-resource:last-child {
      margin-bottom: 0;
    }
    & > label {
      width: 70px;
      text-align: right;
    }
    & > div {
      flex: 1;
      display: inline-flex;
      flex-direction: row;
      margin-left: 10px;
    }
    &-action {
      cursor: pointer;
      font-size: 24px;
      width: 60px;
      &--del {
        color: #e81123;
      }
      &--add {
        margin-left: 8px;
        color: #009688;
      }
    }
  }

}
</style>